package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/validation"
	httpfacades "github.com/hulutech-web/http_result"
	"goravel/app/models"
)

type AuthController struct {
}

type LoginReq struct {
	Mobile   string `json:"mobile" form:"mobile"`
	Password string `json:"password" form:"password"`
}

func NewAuthController() *AuthController {
	return &AuthController{}
}

// Login 用户登录
// @Summary      用户登录
// @Description  用户通过传递mobile和password进行登录
// @Tags         登录
// @Accept       json
// @Produce      json
// @Param        login_req  body  LoginReq  true  "login_req"
// @Success 200 {string} json "{"code":"200", "data":"response data"}"
// @Router       /api/auth/login [post]
func (r *AuthController) Login(ctx http.Context) http.Response {
	validator, _ := facades.Validation().Make(map[string]any{
		"mobile":   ctx.Request().Input("mobile", ""),
		"password": ctx.Request().Input("password", ""),
	}, map[string]string{
		"mobile":   "required",
		"password": "required",
	}, validation.Messages(map[string]string{
		"mobile.required":   "名称不能为空",
		"password.required": "密码不能为空",
	}))
	if validator.Fails() {
		return httpfacades.NewResult(ctx).ValidError("参数错误", validator.Errors().All())
	}

	var user models.User
	err := validator.Bind(&user)
	if err != nil {
		return httpfacades.NewResult(ctx).Error(http.StatusBadRequest, "参数错误", nil)
	}

	//	查询user是否存在
	user_exist := models.User{}
	facades.Orm().Query().Model(&models.User{}).Where("mobile=?", user.Mobile).First(&user_exist)
	if user_exist.ID == 0 {
		return httpfacades.NewResult(ctx).Error(http.StatusBadRequest, "用户不存在", nil)

	} else {
		//	验证密码是否正确
		if !facades.Hash().Check(user.Password, user_exist.Password) {
			return httpfacades.NewResult(ctx).Error(http.StatusBadRequest, "密码错误", nil)

		} else {
			//	生成token
			token, err1 := facades.Auth(ctx).Login(&user_exist)
			if err1 != nil {
				return httpfacades.NewResult(ctx).Success("验证信息失败", nil)
			}
			return ctx.Response().Status(http.StatusOK).Json(http.Json{
				"message": "登录成功",
				"data": struct {
					Token string      `json:"token"`
					User  models.User `json:"user"`
				}{
					Token: token,
					User:  user_exist,
				},
			})
		}
	}
}

// 退出
func (r *AuthController) Logout(ctx http.Context) http.Response {
	err := facades.Auth(ctx).Logout()
	if err != nil {
		return ctx.Response().Status(http.StatusUnprocessableEntity).Json(http.Json{
			"message": "退出失败",
		})
	}
	return ctx.Response().Status(http.StatusOK).Json(http.Json{
		"message": "退出成功",
	})
}

// 注册
func (r *AuthController) Register(ctx http.Context) http.Response {
	type UserForm struct {
		Mobile   string `form:"mobile" json:"mobile"`
		Password string `form:"password" json:"password"`
		Code     string `form:"code" json:"code"`
	}

	var userForm UserForm
	err := ctx.Request().Bind(&userForm)
	if err != nil {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "参数错误", nil)
	}
	var user models.User
	get := facades.Cache().Get(user.Mobile)
	if userForm.Code != get {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "验证码错误", nil)
	}
	if userForm.Mobile == "" || userForm.Password == "" {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "参数错误", nil)
	}
	user.Mobile = userForm.Mobile
	user.Password, _ = facades.Hash().Make(userForm.Password)

	facades.Orm().Query().Where("mobile = ?", user.Mobile).First(&user)
	if user.ID != 0 {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "用户已存在", nil)
	}
	err = facades.Orm().Query().Create(&user)
	if err != nil {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "注册失败", nil)
	}
	return httpfacades.NewResult(ctx).Success("注册成功", nil)
}

// 重置密码
func (r *AuthController) Reset(ctx http.Context) http.Response {
	type UserForm struct {
		Mobile   string `form:"mobile" json:"mobile"`
		Password string `form:"password" json:"password"`
		Code     string `form:"code" json:"code"`
	}

	var userForm UserForm
	err := ctx.Request().Bind(&userForm)
	if err != nil {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "参数错误", nil)
	}
	var user models.User
	user.Mobile = userForm.Mobile
	facades.Orm().Query().Where("mobile = ?", user.Mobile).First(&user)
	if user.ID == 0 {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "用户不存在", nil)
	}

	get := facades.Cache().Get(user.Mobile)
	if get != userForm.Code {
		return httpfacades.NewResult(ctx).Error(http.StatusInternalServerError, "验证码错误", nil)

	}
	pwd, _ := facades.Hash().Make(userForm.Password)
	facades.Orm().Query().Model(&models.User{}).Where("mobile = ?", user.Mobile).Update("password", pwd)
	return httpfacades.NewResult(ctx).Success("重置成功", nil)
}
